package ay.shadow.seckill.service.impl;

import ay.shadow.core.utils.UUIDUtil;
import ay.shadow.seckill.entity.User;
import ay.shadow.seckill.entity.vo.LoginVo;
import ay.shadow.seckill.entity.vo.RespBean;
import ay.shadow.seckill.entity.vo.RespBeanEnum;
import ay.shadow.seckill.mapper.UserMapper;
import ay.shadow.seckill.service.IUserService;
import ay.shadow.core.utils.Md5Util;
import ay.shadow.seckill.utils.CookieUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 暗影
 * @since 2025-02-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = String.valueOf(loginVo.getMobile());
//        System.out.println(mobile);
        String password = loginVo.getPassword();
//        // 参数校验
//        if (StringUtils.isEmpty(mobile)||StringUtils.isEmpty(password)){
//            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
//        }
//        if (!ValidatorUtil.isMobile(mobile)){
//            return RespBean.error(RespBeanEnum.MOBILE_ERROR);
//        }
        // 根据手机号获取用户
        User userEntity = baseMapper.selectById(mobile);
//        log.info("{}", user.toString());
        if (null == userEntity) {
//            log.info("{}", RespBeanEnum.LOGIN_ERROR);
//            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        // 判断密码是否正确
        if (!(Md5Util.formToPass(password, userEntity.getSalt()).equals(userEntity.getPassword()))) {
//            throw new GlobalException(RespBeanEnum.LOGIN_ERROR);
            return RespBean.error(RespBeanEnum.LOGIN_ERROR);
        }
        // 生成cookie
        String ticket = UUIDUtil.uuid();
//        //将uuid-user放入session之中
//        request.getSession().setAttribute(ticket, userEntity);
        redisTemplate.opsForValue().set("user:" + ticket, userEntity);
        CookieUtil.setCookie(request, response, "userTicket", ticket);
        return RespBean.success();
    }

    /**
     * @param userTicket
     * @param request
     * @param response
     * @return
     */
    @Override
    public User getUserByCookie(String userTicket, HttpServletRequest request, HttpServletResponse response) {
        User o = (User) redisTemplate.opsForValue().get("user:" + userTicket);
        return o;
    }
}
